﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ProjectDeal.Models;
using Facebook;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Collections.Specialized;
using System.Configuration;
using ProjectDeal.Helpers;
using System.Data;
using System.Data.Objects;
namespace ProjectDeal.Controllers
{
    public class KhachHangController : Controller
    {
        //
        // GET: /KhachHang/

        db_Kayleehouse db = new db_Kayleehouse();
        public ActionResult DangKi()
        {
            KhachHang objKhachHang = new KhachHang();
            objKhachHang.NgayDangKy = DateTime.Now;
            objKhachHang.NgayThayDoi = DateTime.Now;

            var tinhThanhList = (from b in db.TinhThanhs select b).ToList();
            ViewData["TinhThanh"] = tinhThanhList;
            return View(objKhachHang);
        }
        [Authorize]
        public ActionResult InfoContact()
        {
            Guid UserId =(Guid)Membership.GetUser().ProviderUserKey;
            var KhachHang = from b in db.KhachHangs
                            where b.UserId == UserId
                            select b;
            var tinhThanhList = (from b in db.TinhThanhs select b).ToList();
            ViewData["TinhThanh"] = tinhThanhList;
            var lsQuanHuyen = (from b in db.QuanHuyens
                               select new { b.MaQuanHuyen, b.TenQuanHuyen }).ToList();
            ViewData["QuanHuyen"] = lsQuanHuyen;
            var lsPhuongXa = (from b in db.PhuongXas select new { b.MaPhuongXa, b.TenPhuongXa }).ToList();
            ViewData["PhuongXa"] = lsPhuongXa;
            return View(KhachHang.Single());
        }

        [HttpPost]
        [Authorize]
        public ActionResult InfoContact(KhachHang objKhachHang)
        {
            try
            {
                db.KhachHangs.Add(objKhachHang);
                db.Entry(objKhachHang).State = EntityState.Modified;
                
                db.SaveChanges();
            }
            catch (Exception)
            {
                
                throw;
            }
           
            return View();
        }
        public static IEnumerable<Gender> GetList_Gender()
        {
            List<Gender> lst = new List<Gender> { new Gender { GenderID = true, GenderName = "Nam" } };
            lst.Add(new Gender { GenderID = false, GenderName = "Nữ" });
            return lst;
        }
        
        [HttpPost]
        public ActionResult DangKy(KhachHang objKhachHang,string MatKhau)
        {
            try
            {
                MembershipCreateStatus createStatus;
                var user = Membership.CreateUser(objKhachHang.Email, MatKhau,
                    objKhachHang.Email,null,null,true,out createStatus);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    int temptp = int.Parse(objKhachHang.ThanhPho);
                    int tempqh = int.Parse(objKhachHang.Quan);
                    string thanhpho = (from b in db.TinhThanhs
                                       where b.MaTinhThanh == temptp
                                       select b.TenTinhThanh).Single();
                    string quanhuyen = (from b in db.QuanHuyens
                                        where b.MaQuanHuyen == tempqh
                                        select b.TenQuanHuyen).Single();
                    KhachHang objKh = new KhachHang();
                    objKhachHang.UserId = (Guid)user.ProviderUserKey;
                    objKh.Email = objKhachHang.Email;
                    objKh.GioiTinh = objKhachHang.GioiTinh;
                    objKh.HoTen = objKhachHang.HoTen;
                    objKh.NgayDangKy = DateTime.Now;
                    objKh.NgayThayDoi = DateTime.Now;
                    objKh.ThanhPho = thanhpho;
                    objKh.Quan = quanhuyen;
                    objKh.SoNha = objKhachHang.SoNha;
                    objKh.PhuongXa = objKhachHang.PhuongXa;
                    objKh.DienThoai = objKhachHang.DienThoai;
                    objKh.Duong = objKhachHang.Duong;
                    db.KhachHangs.Add(objKhachHang);
                    db.SaveChanges();
                    
                }
               
            }
            catch (Exception)
            {

                throw;
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult ForgotPassword()
        {
            return View();
        }

        public ActionResult UserLogin()
        {

            return View();
        }
        [HttpPost]
        public ActionResult UserLogin(LogOnModel objLogOn)
        {
            if (Membership.ValidateUser(objLogOn.UserName, objLogOn.Password))
            {
                KhachHang objKhachHang = (from b in db.KhachHangs
                                          where b.Email.Equals(objLogOn.UserName)
                                          select b).Single();
                Session["Logged"] = objKhachHang;
                FormsAuthentication.SetAuthCookie(objLogOn.UserName, true);
                return RedirectToAction("Index", "Home");
            }
            return View();
        }


        public JsonResult GetQuanHuyen(int MaTP)
        {
            var lsQuanHuyen = (from b in db.QuanHuyens
                               where b.MaTinhThanh == MaTP
                               select new {b.MaQuanHuyen,b.TenQuanHuyen }).ToList();
            StringBuilder sb = new StringBuilder();
            sb.Append("<option value=''>Chọn quận huyện</option>");
            foreach (var quanhuyen in lsQuanHuyen)
            {
                sb.Append("<option value='" + quanhuyen.MaQuanHuyen + "'>" + quanhuyen.TenQuanHuyen + "</option>");
            }
            return Json(sb.ToString(), JsonRequestBehavior.AllowGet);
        }


        public JsonResult GetPhuongXa(int MaQuan)
        {
            var lsPhuongXa = (from b in db.PhuongXas
                              where b.MaQuanHuyen == MaQuan
                              select new {b.MaPhuongXa,b.TenPhuongXa }).ToList();
            StringBuilder sb = new StringBuilder();
            sb.Append("<option value=''>Chọn phường/xã</option>");
            foreach (var phuongxa in lsPhuongXa)
            {
                sb.Append("<option value='" + phuongxa.MaPhuongXa + "'>" + phuongxa.TenPhuongXa + "</option>");
            }
            return Json(sb.ToString(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult LoginPopup(string username, string password)
        {
            if (Membership.ValidateUser(username, password))
            {

                KhachHang objKhachHang = (from b in db.KhachHangs
                                          where b.Email.Equals(username)
                                          select b).Single();
                FormsAuthentication.SetAuthCookie(username, true);
    
                Session["Logged"] = objKhachHang;
                return Json(new
                {
                    status = true
                });
            }
            else
            {
                return Json(new
                {
                    status = false
                });
            }

        }
        public ActionResult Loggout()
        {
            FormsAuthentication.SignOut();
            Session.Clear();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult LoginWithFacebook(string code)
        {
            FacebookClient fb = new FacebookClient();

            string host = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority;

            string redirectUrl = host + "/KhachHang/LoginWithFacebook";
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            string fbAppId = appSettings.Get("fbId");
            string fbAppSecret = appSettings.Get("fbSecrect");
            string email = "";
            var request = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&redirect_uri={2}&code={3}",
                fbAppId,
                fbAppSecret,
                redirectUrl,
                code);
            try
            {
                 dynamic getAccess = fb.Get(request);
                fb.AccessToken = getAccess.access_token;

                dynamic user = fb.Get("me");



                var fbUser = new FacebookUser
                {
                    AccessToken = getAccess.access_token,
                    Expires = DateTime.Now.AddSeconds(getAccess.expires),
                    FacebookId = long.Parse(user.id),
                    Name = user.name,
                };
                InMemoryUserStore.Add(fbUser);
                bool gender;
                if (user.gender == "male")
                {
                    gender = true;
                }
                else gender = false;
                 email =Convert.ToString(user.email);
                var isExist = (from b in db.KhachHangs
                               where b.Email.Equals(email)
                               select b);
                MembershipUser mbKhachHang;
                if (!isExist.Any())
                {
                    try
                    {
                        mbKhachHang = Membership.CreateUser(email, Guid.NewGuid().ToString(), email);
                    }
                    catch (Exception ex)
                    {
                        mbKhachHang = Membership.GetUser(email);
                    }
                    string address = "";
                    if (user.location != null) address = user.location.name;
                    try
                    {
                        KhachHang objkh = new KhachHang();
                        objkh.Email = email;
                        objkh.GioiTinh = gender;
                        objkh.HoTen = user.name;
                        objkh.NgaySinh = ConvertBirth(user.birthday);
                        objkh.NgayThayDoi = DateTime.Now;
                        objkh.NgayDangKy = DateTime.Now;
                        objkh.UserId = (Guid)mbKhachHang.ProviderUserKey;
                        objkh.ThanhPho = "Hồ Chí Minh";
                        objkh.AccessToken = getAccess.access_token;
                        db.KhachHangs.Add(objkh);
                        db.SaveChanges();


                    }
                    catch (Exception)
                    {
                        
                        throw;
                    }
                    FormsAuthentication.SetAuthCookie(mbKhachHang.UserName, false);
                    KhachHang currentUser = (from get in db.KhachHangs where get.Email == email select get).Single();
                    if (currentUser.AccessToken != fb.AccessToken)
                    {
                        currentUser.AccessToken = fb.AccessToken;
                        //TODO: co the dua AccessToken vao luc tao user luon
                        db.SaveChanges();
                    }
                    Session["Logged"] = currentUser;
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(isExist.ToList()[0].Email, false);
                    KhachHang currentUser = (from get in db.KhachHangs where get.Email == email select get).Single();
                    if (currentUser.AccessToken != fb.AccessToken)
                    {
                        currentUser.AccessToken = fb.AccessToken;
                        //TODO: co the dua AccessToken vao luc tao user luon
                        db.SaveChanges();
                    }
                    Session["Logged"] = currentUser;
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        
            //Set the forms authentication auth cookie
            //FormsAuthentication.SetAuthCookie(user.email, false);


            //redirect to home page so that user can start using your application      
            return RedirectToAction("Index", "Home");
            
        }
        public static DateTime ConvertBirth(string str)
        {
            try
            {
                return DateTime.Parse(str);
            }
            catch
            {
                return DateTime.MinValue;
            }
            finally
            {
            }
        }
        [HttpGet]
        [ActionName("FacebookLogin")]
        public ActionResult FacebookLogin(string Url)
        {
            //Luu url cua page hien tai
            if (Request.QueryString["Url"] != null)
            {
                Session["RedirectURL"] = Request.QueryString["Url"].ToString();
            }
            else
            {
                Session["RedirectURL"] = "/";
            }

            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            string fbAppId = appSettings.Get("fbId");
            string fbAppSecret = appSettings.Get("fbSecrect");

            string host = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority;

            string redirectUrl = host + "/KhachHang/LoginWithFacebook";


            string redirectToFb = String.Format("https://www.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}&scope={2}&state={3}",
                fbAppId,
                redirectUrl,
                "email,user_birthday,offline_access,publish_stream,user_location",
                redirectUrl);
            return Redirect(redirectToFb);
           
            
        }

        #region QuenMatKhaiView
        public ActionResult QuenMatKhau()
        {
            return View();
        }
        #endregion

        #region ResetMatKhaiView
        public ActionResult ResetMatKhau()
        {
            return View();
        }
        #endregion
        

        //#region Gui email xac nhan (Quen mat khau)
        //public JsonResult SendEmailValidate(string email)
        //{
        //    //Check if email in database
        //    var isExist = (from b in db.KhachHangs
        //                   where b.Email.Equals(email)
        //                   select b.Email).Any();
        //    if (isExist)
        //    {
        //        //Ma hoa EAS
        //        string encrypt = HtmlEncryption.Encrypt(email + ";" + DateTime.Now, "pass");
        //        string urlValid = Request.Url.Authority + "/Account/ResetPassword?Code=" + encrypt;
        //        var displayname = (from b in db.KhachHangs
        //                           where b.Email.Equals(email)
        //                           select b.HoTen).Single();
        //        Server.MapPath("/Content/EmailTemplates/NotificationEvent.html");
        //        EmailHelpers.SendMailManDrill("admin@tapi.vn",
        //            new List<EmailAddress> { new EmailAddress { name = "", email = email } },
        //            displayname, "Khôi phục mật khẩu ở Tapi.vn",
        //            NotificationHelpers.ReccoveryPassword(displayname,
        //            urlValid, Server.MapPath("/Content/EmailTemplates/RecoveryPassword.html")),
        //            email);
        //    }
        //    else
        //    {
        //        email = "";
        //    }

        //    return Json(email, JsonRequestBehavior.AllowGet);
        //}

        //public ActionResult ResetPassword(string code)
        //{

        //    string Email = "";
        //    Email = EncryptHelper.Decrypt(code, "pass");
        //    Email = Email.Remove(Email.IndexOf(';'));
        //    var User = (from b in db.KhachHangs
        //                where b.Email.Equals(Email)
        //                select b).Single();
        //    return View(User);
        //}
        //[HttpPost]
        //public ActionResult ChangeNewPassword(string password, string email)
        //{

        //    MembershipUser user = Membership.GetUser(email);
        //    if (user.IsLockedOut)
        //    {
        //        Membership.Provider.UnlockUser(email);
        //    }
        //    user.ChangePassword(user.ResetPassword(), password);
        //    return RedirectToAction("ChangePasswordSuccess", "Account");
        //}
        //#endregion


    }
    public class FacebookUser
    {
        public long FacebookId { get; set; }
        public string AccessToken { get; set; }
        public DateTime Expires { get; set; }
        public string Name { get; set; }
    }
    public class Gender
    {
        public bool GenderID { get; set; }
        public string GenderName { get; set; }
    }
    public class InMemoryUserStore
    {

        private static System.Collections.Concurrent.ConcurrentBag<FacebookUser> users = new System.Collections.Concurrent.ConcurrentBag<FacebookUser>();

        public static void Add(FacebookUser user)
        {
            if (users.SingleOrDefault(u => u.FacebookId == user.FacebookId) != null)
            {
                //throw new InvalidOperationException("User already exists.");
            }
            else
                users.Add(user);
        }

        public static FacebookUser Get(long facebookId)
        {
            return users.SingleOrDefault(u => u.FacebookId == facebookId);
        }

    }
}
